<?php
namespace app\common\service\member;
use app\common\cache\member\MemberIdCardCache;
use app\common\model\member\MemberIdCardModel;
use app\common\model\member\MemberModel;

/**
 * 用户身份证信息
 */
class MemberIdCardService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
            'id' => '',
        'is_disable' => 0,
        'member_id' => '',
        'card_front_id' => '',
        'card_opposite_id' => '',
        'name' => '',
        'nationality' => '',
        'num' => '',
        'sex' => '',
        'birth' => '',
        'is_face_fake' => 0,
        'address' => '',
        'start_date' => '',
        'end_date' => '',
        'issue' => '',
        'is_back_fake' => 0,
        'card_hand_id' => '',
    ];
    /**
     * 用户身份证信息列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MemberIdCardModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,is_disable,create_time,update_time,member_id,card_front_id,card_opposite_id,auth_status,auth_msg,auth_time,auth_uid,name,nationality,num,sex,birth,is_face_fake,address,start_date,end_date,issue,is_back_fake,card_hand_id,is_3ys_auth';
        }
        // 将字段字符串拆分成数组，并在每个字段前面加上表别名
        $fieldArray = explode(',', $field);
        foreach ($fieldArray as &$f) {
            $f = 'a.' . $f;
        }
        $field = implode(',', $fieldArray);
        if (empty($order)) {
            $order = ['a.'.$pk => 'desc'];
        }
        $with = $append = $hidden = [];
        //用户信息
        if (strpos($field, 'member_id') !== false) {
            $merber_with = ['member'=>function($query){
                $query->with(['avatar'])->append(['avatar_url'])->hidden(['avatar'])->field('member_id,phone,avatar_id,username');
            }];
            $with = array_merge($with,$merber_with);
        }
        //身份证正面
        if (strpos($field, 'card_front_id') !== false) {
            $with[]   = $hidden[] = 'cardFront';
            $append[] = 'card_front_url';
        }
        //身份证反面
        if (strpos($field, 'card_opposite_id') !== false) {
            $with[]   = $hidden[] = 'cardOpposite';
            $append[] = 'card_opposite_url';
        }
        //手持身份证
        if (strpos($field, 'card_hand_id') !== false) {
            $with[]   = $hidden[] = 'cardHand';
            $append[] = 'card_hand_url';
        }

        //用户名和手机号查询
        $model = $model->alias('a');
        foreach ($where as $k=>$v){
            if ($v[0] == 'username' || $v[0] == 'phone'){
                $model = $model->join('ya_member m', 'm.member_id=a.member_id')->where('m.'.$v[0], $v[1], $v[2]);
                unset($where[$k]);
            }else{
                $where[$k][0] = 'a.'.$v[0];
            }
        }
        if ($page == 0 || $limit == 0) {
            return $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        //身份证日期处理
        if (strpos($field, 'birth') !== false) {
            foreach ($list as $key=>$val){
                if(isset($val['birth']) && $val['birth']){
                    $list[$key]['birth'] = date('Y年m月d日', strtotime($val['birth']));
                }
                if(isset($val['start_date']) && $val['start_date']){
                    $list[$key]['start_date'] = date('Y.m.d', strtotime($val['start_date']));
                }
                if(isset($val['end_date']) && $val['end_date']){
                    $list[$key]['end_date'] = date('Y.m.d', strtotime($val['end_date']));
                }
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    /**
     * 用户身份证信息信息
     *
     * @param int  $id   用户身份证信息id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = MemberIdCardCache::get($id);
        if (empty($info)) {
            $model = new MemberIdCardModel();
            $with =  $hidden = ['cardFront','cardOpposite','cardHand'];
            $append = ['card_front_url','card_opposite_url','card_hand_url'];
            $info = $model->where('member_id',$id)->with($with)->append($append)->hidden($hidden)->find();
            if (empty($info)) {
                if ($exce) {
                    exception('身份证信息不存在：' . $id);
                }
                return [];
            }
            $info = $info->toArray();
            MemberIdCardCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 用户身份证信息添加
     *
     * @param array $param 用户身份证信息信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new MemberIdCardModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();
        $model->save($param);
        $id = $model->$pk;
        if (empty($id)) {
            exception();
        }
        $param[$pk] = $id;
        return $param;
    }
     /**
     * 用户身份证信息修改
     *
     * @param int|array $ids   用户身份证信息id
     * @param array     $param 用户身份证信息信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new MemberIdCardModel();
        $pk = $model->getPk();
        if(isset($param['member_id'])){
            MemberIdCardCache::del($param['member_id']);
            $member_data=[];
            if(isset($param['name']) && $param['name']){
                $member_data['name'] =$param['name'];
            }
            if(isset($param['sex']) && $param['sex']){
                $member_data['gender'] =$param['sex']=='男'?1:($param['sex']=='女'?2:0);
            }
            if($member_data){
                $member_edit =MemberModel::where('member_id',$param['member_id'])->update($member_data);
            }
        }
        unset($param[$pk], $param['ids'], $param['member_id']);
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        MemberIdCardCache::del($ids);

        return $param;
    }
    /**
     * 用户身份证信息删除
     *
     * @param array $ids  用户身份证信息id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new MemberIdCardModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        MemberIdCardCache::del($ids);
        return $update;
    }

    /**
     * 用户身份证信息保存
     * @Author: 易军辉
     * @DateTime:2024-08-01 19:49
     * @param $member_id
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function save($member_id, $param = [])
    {
        $model = new MemberIdCardModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['member_id']);

        // 查找是否已有记录
        $existingModel = $model->where('member_id', $member_id)->find();

        if (!$existingModel) {
            // 创建新记录
            $param['member_id'] = $member_id;
            $param['create_uid']  = $member_id;
            $param['create_time'] = datetime();
            $model = new MemberIdCardModel($param);
            $result = $model->save();
        } else {
            // 更新已有记录
            $param['update_uid']  = $member_id;
            $param['update_time'] = datetime();
            $result = $existingModel->save($param);
            $model = $existingModel; // 使用已存在的模型实例
        }

        // 检查保存操作的结果
        if (!$result) {
            exception('保存操作失败');
        }

        $id = $model->$pk;
        if (empty($id)) {
            exception('保存操作失败');
        }

        $param[$pk] = $id;
        MemberIdCardCache::del($member_id);
        return $param;
    }

    /**
     * 审核
     * @Author: 易军辉
     * @DateTime:2024-08-02 12:04
     * @param $ids
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function auth($ids, $param = [])
    {
        $model = new MemberIdCardModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $list = $model
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->where($pk, 'in', $ids)
            ->select();
        if(count($list)<=0){
            exception("未有符合条件的记录需要审核");
        }
        // 启动事务
        $model->startTrans();
        try {
            foreach ($list as $k=>$v){
                $v->auth_time=datetime();
                $v->auth_uid=user_id();
                $member_data = [
                    'is_authentication'=>0,
                    'update_uid'=>$v->auth_uid,
                    'update_time'=>$v->auth_time
                ];
                switch (intval($param['auth_status'])){
                    case 0://未上传
                        $v->auth_status=0;
                        break;
                    case 1://待审核
                        $v->auth_status=1;
                        break;
                    case 2://审核通过
                        $v->auth_status=2;
                        $member_data['is_authentication'] =1;
                        $member_data['name'] =$v['name'];
                        if(isset($v['sex']) && $v['sex']){
                            $member_data['gender'] =$v['sex']=='男'?1:($v['sex']=='女'?2:0);
                        }
                        break;
                    case 3://审核未通过
                        $v->auth_status=3;
                        $v->auth_msg=$param['auth_msg'];
                        break;
                }
                $member_edit =MemberModel::where('member_id',$v['member_id'])->update($member_data);
                $v->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $ids;
        MemberIdCardCache::del($ids);
        return $param;
    }
}
